import classNames from 'classnames';
import React, { useContext } from 'react';
import RowContext from './RowContext';
import { ColSize, YmColProps } from './interface';
// 全是flex布局样式

function parseFlex(flex: number | string): string {
  if (typeof flex === 'number') {
    return `${flex} ${flex} auto`;
  }

  if (/^\d+(\.\d+)?(px|em|rem|%)$/.test(flex)) {
    return `0 0 ${flex}`;
  }

  return flex;
}

const colSizes = ['xs', 'sm', 'md', 'lg', 'xl', 'xxl'] as const;
const Col: React.FC<YmColProps> = (props) => {
  const { gutter, wrap } = useContext(RowContext);

  const {
    span,
    order,
    offset,
    className,
    children,
    flex,
    style,
    prefixCls = 'ym-col',
    ...others
  } = props;

  let sizeClassObj = {};
  colSizes.forEach((size) => {
    let sizeProps: ColSize = {};
    const propSize = props[size];
    if (typeof propSize === 'number') {
      sizeProps.span = propSize;
    } else if (typeof propSize === 'object') {
      sizeProps = propSize || {};
    }

    delete others[size];

    sizeClassObj = {
      ...sizeClassObj,
      [`${prefixCls}-${size}-${sizeProps.span}`]: sizeProps.span !== undefined,
      [`${prefixCls}-${size}-order-${sizeProps.order}`]:
        sizeProps.order || sizeProps.order === 0,
      [`${prefixCls}-${size}-offset-${sizeProps.offset}`]:
        sizeProps.offset || sizeProps.offset === 0,
    };
  });

  const mergedStyle: React.CSSProperties = {};
  // Horizontal gutter use padding
  if (gutter && typeof gutter[0] === 'number' && gutter[0] > 0) {
    const horizontalGutter = gutter[0] / 2;
    mergedStyle.paddingLeft = horizontalGutter;
    mergedStyle.paddingRight = horizontalGutter;
  }

  if (flex) {
    mergedStyle.flex = parseFlex(flex);

    // Hack for Firefox to avoid size issue
    // https://github.com/ant-design/ant-design/pull/20023#issuecomment-564389553
    if (wrap === false && !mergedStyle.minWidth) {
      mergedStyle.minWidth = 0;
    }
  }

  const classes = classNames(
    prefixCls,
    {
      [`${prefixCls}-${span}`]: span !== undefined,
      [`${prefixCls}-order-${order}`]: order,
      [`${prefixCls}-offset-${offset}`]: offset,
    },
    className,
    sizeClassObj,
  );

  return (
    <div {...others} style={{ ...mergedStyle, ...style }} className={classes}>
      {children}
    </div>
  );
};

export default Col;
